<?php

include_once('class.mysql.php');

class Login
{
    private $comtec_id_user;
    private $username;
    private $password;
    private $passwmd5;

    private $_errors;
    private $_access;
    private $_login;
    private $_token;

    public function __construct()
    {
        $this->_errors  = array();
        $this->_login   = isset($_POST['login'])? 1 : 0;
        $this->_access  = 0;
        $this->_token   = isset($_POST['token'])? $_POST['token'] : NULL;
        $this->comtec_id_user = 0;

        if($this->_login){
         $this->username = isset ($_POST['username'])? $_POST['username']: NULL;
         $this->password = isset ($_POST['password'])? $_POST['password']: NULL;
         $this->passwmd5 = md5($this->password);
        }else{         
         $this->username = isset ($_SESSION['username'])? $_SESSION['username']: NULL;
         $this->password = NULL;
         $this->passwmd5 = isset ($_SESSION['password'])? $_SESSION['password']: NULL;
        }

    }

    public function isLoggedIn()
    {
        ($this->_login)? $this->verifyPost() : $this->verifySession();

        return $this->_access;
    }

    public function verifyPost()
    {
        try
        {
            if(!$this->isTokenValid())
                throw new Exception('Formulario inv&aacute;lido');

            if(!$this->isDataValid())
                throw new Exception('Datos inv&aacute;lidos');

            if(!$this->verifyDatabase())
                throw new Exception('Nombre de usuario y contrase&ntilde;a inv&aacute;lidos');

            $this->_access = 1;
            $this->registerSession();
        }
        catch (Exception $e)
        {
            $this->_errors[] = $e->getMessage();
        }
    }

    public function verifySession()
    {
        if($this->sessionExist() && $this->verifyDatabase())
            $this->_access = 1;
    }

    public function verifyDatabase()
    {
     $db = new MySQL();
     $tsql = "SELECT comtec_id_user FROM users WHERE status_reg=1 AND email = '$this->username' AND passwmd5 = '$this->passwmd5'";
     $stmt = $db->query($tsql);  
     if ($db->num_rows($stmt))
     {
      list($this->comtec_id_user) = @array_values($db->fetch_assoc($stmt));
      return true;
     }
     else
     { return false; }
    }

    public function isDataValid()
    {
        return (preg_match('/^[a-zA-Z0-9@.]/',$this->username) && preg_match('/^[a-zA-Z0-9@.]/',$this->password))? 1 : 0;
    }

    public function isTokenValid()
    {
        return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token'])? 0 : 1;
    }

    public function registerSession()
    {
    
        if (isset($_POST['remember_me']))
        {
            setcookie("session_id",$this->comtec_id_user,time()+60*60*24*30,"/");
        }
        else
        {
            $_SESSION['comtec_id_user'] = $this->comtec_id_user;
        }
    }

    public function isCookieSet()
    {
        return (isset($_COOKIE['session_id']) && $_COOKIE['session_id'] != "")? 1 : 0;
    }

    public function sessionExist()
    {
        return (isset($_SESSION['comtec_id_user']))? 1 : 0;
        /*return (isset($_SESSION['cid']) || isset($_COOKIE['session_id']))? 1 : 0;*/
    }

    public function showErrors()
    {
        echo "<h3>Errores</h3>";
        foreach($this->_errors as $key=>$value)
            echo $value."<br>";
    }

    public function giveId()
    {
        if (isset($_SESSION['comtec_id_user']))
            return $_SESSION['comtec_id_user'];

        if (isset($_COOKIE['session_id']))
            return $_COOKIE['session_id'];

        return $this->comtec_id_user;
    }
}

?>
